#include "save.h"

#include <QDateTime>

Save::Save(const QString &user)
{
    DB = QSqlDatabase::addDatabase("QSQLITE");
    DB.setDatabaseName("./data/chatting records/" + user + ".db");//
    if (!DB.open()){//连接 没有就创建
        qDebug() << "无法打开数据库：";
    }
    query = new QSqlQuery(DB);
}

void Save::reopen(const QString &user)
{
    if (DB.databaseName() == user){
        return;
    }
    DB.close();
    DB.setDatabaseName("./data/chatting records/" + user + ".db");//设置要连接的数据库的地址

    // 重新打开连接
    if (!DB.open()) {
        qDebug() << "Failed to open new database.";
        return ;
    }
    return;
}

Save &Save::Instance(const QString &user)
{
    static Save s(user);
    if (user != "0"){
        s.reopen(user);
    }
    return s;
}

void Save::createForm(const QString &name)
{
    // QSqlQuery query(DB);
    // 安全转义表名
    QString escapedName = QSqlDatabase::database().driver()->escapeIdentifier(name, QSqlDriver::TableName);
    static QString s = R"(CREATE TABLE %1 (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        sender VARCHAR(20) NOT NULL,
        send_time DATETIME NOT NULL,
        message_content TEXT NOT NULL,
        message_type INTEGER  NOT NULL
    );)";//发送者 发送时间 发送内容 消息类型  //1普通文本 2图片 3视频 4其他
    if (!query->exec(s.arg(escapedName))){
        // qDebug() << "Error 创建表:" << query->lastError().text();
    }
}

void Save::Add(const QString &name, const Message &message)
{
    // static QSqlQuery query(DB);

    // 安全转义表名
    QString escapedName = QSqlDatabase::database().driver()->escapeIdentifier(name, QSqlDriver::TableName);

    query->prepare("INSERT INTO " + escapedName + " (sender, send_time, message_content, message_type) "
                                          "VALUES (?, ?, ?, ?)");

    // 绑定值
    query->addBindValue(message.sender);
    query->addBindValue(QDateTime::currentDateTime().toString(Qt::ISODate));
    query->addBindValue(message.text);
    query->addBindValue(message.type);

    // 执行查询
    bool result = query->exec();
    if (!result) {
        qDebug() << "Error 添加数据:" << query->lastError().text();
    }
}

int Save::getSun(const QString &name) const
{
    // static QSqlQuery query(DB);
    QString s = "SELECT COUNT(*) FROM %1";
    // 安全转义表名
    QString escapedName = QSqlDatabase::database().driver()->escapeIdentifier(name, QSqlDriver::TableName);
    // 查询表中的记录总数
    query->prepare(s.arg(escapedName));
    if (!query->exec()) {
        qDebug() << "Error executing count query: " << query->lastError();
        return -1;
    }
    if (query->next()) {
        int totalRecords = query->value(0).toInt();
        return totalRecords;
    }
    return -1;
}

QStringList Save::getTables() const
{
    return DB.tables();
}

void Save::ReadALine(const int id, const QString &name, Message &message)
{
    // 安全转义表名
    QString escapedName = QSqlDatabase::database().driver()->escapeIdentifier(name, QSqlDriver::TableName);
    query->prepare("SELECT * FROM " + escapedName + " WHERE id =?");
    query->addBindValue(id);
    if (!query->exec()) {
        qDebug() << "Error executing query: " << query->lastError();
    }

    if (!query->next()) {
        qDebug() << "No record found for ID:" << id;
    }

    message.sender = query->value(1).toString();
    message.time = query->value(2).toString();
    message.text = query->value(3).toString();
    message.type = query->value(4).toInt();
}
